// ...........................................................................................................
// (C) Copyright  1996/2008 Fuego Inc.  All Rights Reserved
// THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE OF Fuego Inc.
// The copyright notice above does not evidence any actual or intended
// publication of such source code.
//
// Last changed on 2008-01-11 18:00:34 (-0300), by: machaval. $Revision$
// ...........................................................................................................

package com.webcamtracker.video.polling;

import com.webcamtracker.image.ImageProvider;
import com.webcamtracker.video.VideoSuscriptionSupport;
import com.webcamtracker.video.VideoSuscriptor;

import java.awt.image.BufferedImage;

public class VideoPollingService
        implements Runnable {
    //~ Instance fields ......................................................................................

    private long frameSample = 10L;
    private ImageProvider provider;
    private volatile boolean run = true;
    private Thread thread;
    private VideoSuscriptionSupport videoSuscriptionSupport;

    //~ Constructors .........................................................................................

    public VideoPollingService(ImageProvider provider) {
        this.provider = provider;
        videoSuscriptionSupport = new VideoSuscriptionSupport();
    }

    //~ Methods ..............................................................................................

    public void addVideoSuscriptor(VideoSuscriptor videoSuscriptor) {
        videoSuscriptionSupport.addVideoSuscriptor(videoSuscriptor);
    }

    public void run() {
        while (run) {
            BufferedImage imageToProcess = provider.getImage();
            videoSuscriptionSupport.deliveryFrame(imageToProcess);

            try {
                Thread.sleep(frameSample);
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void stopService() {
        if (!run) {
            run = false;

            try {
                thread.join();
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println("Thread Ended");
        }
    }

    public void startService() {
        run = true;
        System.out.println("Start Consumer");
        thread = new Thread(this);
        thread.start();
    }
}
